<template>
  <view class="reg-view">
    <view>
      <!-- 提示信息弹窗 -->
      <uni-popup ref="message" type="message">
        <uni-popup-message :type="data.msgType" :message="data.messageText" :duration="2000"></uni-popup-message>
      </uni-popup>
    		</view>
    <!-- 邮箱登录 -->
    <view class="reg-tag">
      <view class="trip-index"></view>
      邮箱{{data.work}}
    </view>
    <!-- 邮箱和密码输入 -->
    <view>
      <view class="input-box">
        <input v-model="data.mailAccount" class="l-input" type="text" placeholder="邮箱号" :disabled="data.canInputMailAccount"/>
      </view>
      <view class="input-box">
        <input v-model="data.mailCode" class="l-input" type="number" placeholder="验证码"/>
        <view class="get-code" @click="getMailCode">{{data.codeText}}</view>
      </view>
    </view>
    
    
    <!-- 登录按钮 -->
    <view class="reg-act-box">
      <button class="s-button" @click="checkCode">{{data.work}}</button>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref,toRefs } from 'vue';
import helper from '../../common/helper';
import {onLoad} from '@dcloudio/uni-app'

const data = reactive({
  mailAccount:"",
  mailCode:"",
  msgType:"",
  messageText:"",
  codeText:"获取验证码",
  work:"注册",
  canInputMailAccount: false
});

onLoad((options)=>{
  data.mailAccount = options.mailAccount
  data.work = options.work
  if(data.work == "重置密码" || data.work == "注销账号"){
    data.canInputMailAccount = true
  }
})

//注册
function checkCode(){
  console.log("验证验证码")
  // 验证邮箱和验证码是否填写
  if(data.mailAccount != null && data.mailAccount.trim() != "" && data.mailCode != null && data.mailCode.trim() != ""){ 
    uni.request({
        url: helper.webUrl+'/user/checkMailCode', 
        method:'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded' 
        },
        data: {
          mailAccount: data.mailAccount,
          code:data.mailCode,
          work: data.work
        },
        success: (res) => {
          console.log(res.data);
          if(res.data.code == 200){
            messageToggle("success",res.data.msg)
            if(data.work == "注销账号"){
              uni.removeStorageSync("curUser")
              uni.navigateBack({
              	delta: 2
              });
              return
            }
            uni.navigateTo({
              url:`/subpages/setPassword/setPassword?mailAccount=${data.mailAccount}&work=${data.work}`
            })
          }else{
            messageToggle("info",res.data.msg)
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
        }
    });
  }
}

//验证邮箱格式
function validateEmail(email) {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return emailRegex.test(email);
}

const message = ref(null)

function messageToggle(type,text) {
  data.msgType = type
  data.messageText = text
  message.value.open()
}

const isDisabled  = ref(false)

//获取验证码
function getMailCode(){
  console.log("获取验证码...")
  
  if(data.mailAccount!=null && data.mailAccount.trim()!=""){
    //验证邮箱的格式是否正确
    if(!validateEmail(data.mailAccount)){
      // console.log("邮箱格式不正确")
      messageToggle("info","邮箱格式错误!")
    }else{
      if(data.work == "重置密码"){
        let curUser = uni.getStorageSync("curUser") || null
        if(curUser != null){        
          if(data.mailAccount != curUser.mailAccount){
            messageToggle("info","非账号邮箱!");
            return
          }
        }
      }
      //发送请求到后端，给邮件发送验证码
      if(isDisabled.value){
        return
      }
      
      isDisabled.value = true; 
      let timer;
      let countdown = 60;
      
      // 开始倒计时
      timer = setInterval(() => {
          countdown--;
          data.codeText = `${countdown}秒后重新发送`;
      
          if (countdown <= 0) {
              clearInterval(timer);
              // 重置按钮状态
              isDisabled.value = false
              data.codeText = '获取验证码';
              countdown = 60; // 重置倒计时
          }
      }, 1000);
          
      uni.request({
          url: helper.webUrl+'/user/getMailCode', 
          method:'GET',
          header: {
              'custom-header': 'hello' //自定义请求头信息
          },
          data: {
            mailAccount: data.mailAccount,
            work: data.work
          },
          success: (res) => {
            console.log(res.data);
            if(res.data.code == 200){
              messageToggle("success",res.data.msg)
            }else{
              messageToggle("info",res.data.msg)
            }
          },
          fail: (err) => {
            console.error('请求失败:', err);
          }
      });
    }
  }
}
</script>

<style>
.reg-view{
  width: 100vw;
  height: 100vh;
  background-color: #f4f4f4;
}
.reg-tag{
  font-size: 25px;
  padding: 20px;
  display: flex;
  align-items: center;
}
.trip-index{
  width:5px;
  height: 25px;
  background-color: #89C0FF;
  margin-right: 10px;
}
.input-box{
  width: 80%;
  height: 45px;
  display: flex;
  align-items: center; /* 垂直居中 */
  margin-inline: auto;
  border-radius: 10px;
  background-color: #fff; 
  margin-top: 15px;
}
.l-input{
 margin-left: 2%;
 width: 100%;
 height: 100%;
}
.get-code{
  width: 120px;
}
.reg-act-box{
  display: flex;
  width: 90%;
  margin-inline: auto;
}
.s-button{
  width: 45%;
  background-color: #89C0FF;
  color: #fff;
  font-size: 16px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}
</style>
